//
//  HttpConectionObject.m
//  jetplayerTestProject
//
//  Created by ott on 14-7-26.
//  Copyright (c) 2014年 ott. All rights reserved.
//

#import "HttpConectionObject.h"
#import "SPRequest.h"

@implementation HttpConectionObject

//@synthesize m_delegate;
//@synthesize m_request;

- (void) dealloc
{
    [_conection cancel];
//    [m_request release];
//    [m_conection release];
//    [_receiveData release];
//    [super dealloc];
}

-(id) initWithRequest:(SPRequest *)request delegate:(id<HttpConectionDelegate>)delegate
{
    if (self = [super init])
    {
        _delegate = delegate;
        _request = request;
        _totalBytes = 0;
        _sendBytes = 0;
        _conection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    }
    return self;
}

- (void) start
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_conection start];
    });
    
}

- (void) cancel
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_conection cancel];
        self.request.delegate = nil;
        
        if ([_delegate respondsToSelector:@selector(httpConectionHasCanceled:)])
        {
            [_delegate httpConectionHasCanceled:self];
        }
    });
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    NSLog(@"send request start*****************");
    NSLog(@"http url:%@",request.URL);
    NSLog(@"http method:%@",request.HTTPMethod);
    NSLog(@"http allHTTPHeaderFields:%@",request.allHTTPHeaderFields);
    NSLog(@"http body:%@",[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
    NSLog(@"send request end*****************");
    
    
    if (_receiveData)
    {
        _receiveData = nil;
    }
    _receiveData = [[NSMutableData alloc] init];
    
    return request;
}

//http状态响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

    NSLog(@"handle respond start#######################");
    NSLog(@"http return code:%ld",httpResponse.statusCode);
    NSLog(@"http header:%@", httpResponse.allHeaderFields);
    
    if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300)
    {
        _totalBytes = [[[httpResponse allHeaderFields] objectForKey:@"Content-Length"] longLongValue];
        //ok
    }
    else if (httpResponse.statusCode >= 300 && httpResponse.statusCode < 400)
    {
        //重定向等细化处理
    }
//    else if (httpResponse.statusCode >= 400 && httpResponse.statusCode < 500)
//    {
//        //客户端错误
//        [_conection cancel];
//        if (_delegate && [_delegate respondsToSelector:@selector(httpConection:didFaild:)])
//        {
//            NSError *error = [[NSError alloc] initWithDomain:@"HttpResponseDomain" code:httpResponse.statusCode userInfo:[NSDictionary dictionaryWithObject:@"无效的请求" forKey:NSLocalizedFailureReasonErrorKey]];
//            [_delegate httpConection:self didFaild:error];
//        }
//        
//    }
//    else if (httpResponse.statusCode >= 500 && httpResponse.statusCode < 600)
//    {
//        //服务器错误
//        [_conection cancel];
//        if (_delegate && [_delegate respondsToSelector:@selector(httpConection:didFaild:)])
//        {
//            NSError *error = [[NSError alloc] initWithDomain:@"HttpResponseDomain" code:httpResponse.statusCode userInfo:[NSDictionary dictionaryWithObject:@"服务器错误" forKey:NSLocalizedFailureReasonErrorKey]];
//            [_delegate httpConection:self didFaild:error];
//        }
//    }
//    else
//    {
//        //未知错误
//        [_conection cancel];
//        if (_delegate && [_delegate respondsToSelector:@selector(httpConection:didFaild:)])
//        {
//            NSError *error = [[NSError alloc] initWithDomain:@"HttpResponseDomain" code:httpResponse.statusCode userInfo:[NSDictionary dictionaryWithObject:@"未知错误" forKey:NSLocalizedFailureReasonErrorKey]];
//            [_delegate httpConection:self didFaild:error];
//        }
//    }
}

//接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (data.length > 0)
    {
        [_receiveData appendData:data];
        
        _sendBytes = [_receiveData length];
        
        if (_delegate && [_delegate respondsToSelector:@selector(httpConection:totalBytes:sendBytes:)])
        {
            [_delegate httpConection:self totalBytes:_totalBytes sendBytes:_sendBytes];
        }
    }
}

//请求完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responString = [[NSString alloc] initWithData:_receiveData encoding:NSUTF8StringEncoding];
    if (responString)
        NSLog(@"handel respond:%@",responString);
    NSLog(@"handle respond end#######################");
    
    if (_delegate && [_delegate respondsToSelector:@selector(httpConection:didFinish:)])
    {
        [_delegate httpConection:self didFinish:_receiveData];
    }
    
}

//请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(httpConection:didFaild:)])
    {
        [_delegate httpConection:self didFaild:error];
    }
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{
    return YES;
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        //if ([trustedHosts containsObject:challenge.protectionSpace.host])
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
             forAuthenticationChallenge:challenge];
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

@end
